package com.ruoyi.oto.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.PageQueryDTO;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.oto.constants.*;
import com.ruoyi.oto.domain.BranchMember;
import com.ruoyi.oto.domain.CompanyCore;
import com.ruoyi.oto.domain.CompanyTags;
import com.ruoyi.oto.domain.CompanyTagsCore;
import com.ruoyi.oto.domain.dto.CompanyTagCoreQuryDTO;
import com.ruoyi.oto.domain.dto.CompanyTagUpdateDTO;
import com.ruoyi.oto.domain.dto.SubmitApplyTagValueDTO;
import com.ruoyi.oto.domain.dto.TagsCoreDTO;
import com.ruoyi.oto.mapper.CompanyTagsCoreMapper;
import com.ruoyi.oto.service.BranchMemberService;
import com.ruoyi.oto.service.CompanyCoreService;
import com.ruoyi.oto.service.CompanyTagsCoreService;
import com.ruoyi.oto.service.CompanyTagsService;
import com.ruoyi.oto.tagvisible.BranchTagVisible;
import com.ruoyi.oto.tagvisible.CompanyTagVisible;
import com.ruoyi.oto.tagvisible.TagVisible;
import com.ruoyi.oto.tagvisible.TagVisibleRange;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 企业服务
 *
 * @author ruoyi
 */
@Service
public class CompanyTagsCoreServiceImpl extends ServiceImpl<CompanyTagsCoreMapper, CompanyTagsCore> implements CompanyTagsCoreService
{
    @Autowired
    private CompanyCoreService companyCoreService;

    @Autowired
    private CompanyTagsService companyTagsService;

    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private BranchMemberService branchMemberService;
    @Autowired
    private CompanyTagsCoreService companyTagsCoreService;

    /**
     * 分页查询企业标签
     * @param sysUser
     * @param quryDTO
     * @param page
     * @return
     */
    @Override
    public IPage<CompanyTagsCore> pageTags(SysUser sysUser, CompanyTagCoreQuryDTO quryDTO, IPage<CompanyTagsCore> page) {
        IPage<CompanyTagsCore> companyTagsCoreIPage = this.page(page, new LambdaQueryWrapper<CompanyTagsCore>().like(StrUtil.isNotEmpty(quryDTO.getTagName()), CompanyTagsCore::getTagName, quryDTO.getTagName())
                .eq(quryDTO.getTagType() != null, CompanyTagsCore::getTagType, quryDTO.getTagType())
                .eq(!sysUser.isAdmin(),CompanyTagsCore::getBranchId,sysUser.getDeptId())
                .eq(CompanyTagsCore::getDelFlag,DeleteFlag.NO));
        companyTagsCoreIPage.getRecords().forEach(ctc->{
            ctc.setEditable(ctc.getBranchId().equals(sysUser.getDeptId()));
        });
        return companyTagsCoreIPage;
    }

    /**
     * 保存企业标签
     * @param tagsCoreDTO
     */
    @Override
    public CompanyTagsCore saveCompanyTagsCore(TagsCoreDTO tagsCoreDTO,@NotNull LoginUser loginUser) {
        boolean isUpdate = tagsCoreDTO.getId()!=null;  //有Id就是更新操作
        //查询是否有相同名字的标签
        CompanyTagsCore exist = this.getOne(new LambdaQueryWrapper<CompanyTagsCore>().eq(CompanyTagsCore::getTagName, tagsCoreDTO.getTagName()));
        if(!isUpdate && exist!=null) {
            throw new ServiceException("标签名已经存在，请换个其他名字");

        }
        if(isUpdate && exist!=null && !exist.getBranchId().equals(loginUser.getDeptId())){
            throw new ServiceException("您没有此标签的修改权限");
        }
        if(!isUpdate){  //新增
            CompanyTagsCore newCompanyTagsCore = new CompanyTagsCore();
            newCompanyTagsCore.setCreateBy(loginUser.getUsername());
            newCompanyTagsCore.setCreateTime(new Date());
            newCompanyTagsCore.setDelFlag(DeleteFlag.NO);
            newCompanyTagsCore.setTagName(tagsCoreDTO.getTagName());
            newCompanyTagsCore.setTagType(tagsCoreDTO.getTagType());
            newCompanyTagsCore.setTagUnit(tagsCoreDTO.getTagUnit());
            if(TagType.选择 == newCompanyTagsCore.getTagType()){
                if(ObjUtil.isEmpty(tagsCoreDTO.getTagOptions())){
                    throw new ServiceException("选择标签要设置待选值");
                }
                newCompanyTagsCore.setTagOptions(String.join(",", Arrays.asList(tagsCoreDTO.getTagOptions().split("\n"))));
            }
            if(TagType.是否显示==newCompanyTagsCore.getTagType()){
                newCompanyTagsCore.setTagOptions("显示,不显示");
            }
            newCompanyTagsCore.setIsApply(tagsCoreDTO.getIsApply()?1:0);
            newCompanyTagsCore.setBranchId(loginUser.getDeptId());
            newCompanyTagsCore.setVisible(tagsCoreDTO.getVisible());
            newCompanyTagsCore.insert();
            return newCompanyTagsCore;
        }
        else{
            exist = this.getOne(new LambdaQueryWrapper<CompanyTagsCore>().eq(CompanyTagsCore::getId, tagsCoreDTO.getId()).eq(CompanyTagsCore::getBranchId, loginUser.getDeptId()));
            if(ObjUtil.isNull(exist)){
                throw new ServiceException("标签不存在或者您没有修改权限");
            }
            exist.setDelFlag(DeleteFlag.NO);
            exist.setTagName(tagsCoreDTO.getTagName());
            exist.setTagType(tagsCoreDTO.getTagType());
            exist.setTagUnit(tagsCoreDTO.getTagUnit());
            if(TagType.选择 == exist.getTagType()){
                if(ObjUtil.isEmpty(tagsCoreDTO.getTagOptions())){
                    throw new ServiceException("选择标签要设置待选值");
                }
                exist.setTagOptions(String.join(",", Arrays.asList(tagsCoreDTO.getTagOptions().split("\n"))));
            }
            if(TagType.是否显示==exist.getTagType()){
                exist.setTagOptions("显示,不显示");
            }
            exist.setIsApply(tagsCoreDTO.getIsApply()?1:0);
            exist.setVisible(tagsCoreDTO.getVisible());
            exist.updateById();
            return exist;
        }

    }

    /**
     * 删除企业标签
     * @param tagIds
     * @param loginUser
     * @return
     */
    @Override
    public boolean deleteCompanyTagsCore(List<Long> tagIds, LoginUser loginUser) {
        if(tagIds.isEmpty()){
            throw new ServiceException("没有要删除的标签");
        }
        List<CompanyTagsCore> deleteTags = this.listByIds(tagIds);
        List<CompanyTagsCore> myDeleteTags = deleteTags.stream().filter(tag -> tag.getBranchId().equals(loginUser.getDeptId())).collect(Collectors.toList());
        myDeleteTags.forEach(tag->{
                               tag.setDelFlag(DeleteFlag.YES);
                               tag.setUpdateBy(loginUser.getUsername());
                               tag.setUpdateTime(new Date());});
        return this.updateBatchById(myDeleteTags);
    }

    /**
     * 获取待审核的标签
     * @param pageQueryDTO
     * @param loginUser
     * @return
     */
    @Override
    public IPage<CompanyTags> listChangedCompanyTags(PageQueryDTO pageQueryDTO, LoginUser loginUser) {
        IPage<CompanyTags> page = new Page<>(pageQueryDTO.getCurrent(), pageQueryDTO.getSize());
        CompanyTags companyTags = new CompanyTags();
        //条件  当前部门，要审核，审核状态为CompanyTagApplyStatus.未审核的
        IPage<CompanyTags> result = companyTags.selectPage(page,new LambdaQueryWrapper<CompanyTags>().eq(CompanyTags::getBranchId,loginUser.getDeptId())
                                                            .eq(CompanyTags::getIsApply, YesNoFlag.YES)
                                                            .eq(CompanyTags::getApplyStatus, CompanyTagApplyStatus.未审核));
        result.getRecords().forEach(ctc->{
            //获取公司名称
            CompanyCore companyCore = companyCoreService.getById(ctc.getCompanyId());
            if(ObjUtil.isNotNull(companyCore)){
                ctc.setCompanyName(companyCore.getCompanyName());
            }
            //处理显示Tag showTag
            if(ctc.getTagType()==TagType.文本 || ctc.getTagType()==TagType.选择)
            {
                ctc.setShowTag(ctc.getTagName()+" "+ ctc.getTagValue() + " " + ctc.getTagUnit() );
            }
            else if(ctc.getTagType()==TagType.数字){
                ctc.setShowTag(ctc.getTagName()+" "+ ctc.getTagValueInt() + " "+ ctc.getTagUnit());
            }
            else if(ctc.getTagType()==TagType.是否显示){
                ctc.setShowTag(ctc.getTagName()+" "+ctc.getTagValue());
            }
            else {
                ctc.setShowTag("");
            }
        });
        return result;
    }

    /**
     * 审核已改变的标签
     * @param applyTagValueDTO
     * @param loginUser
     */
    @Override
    public void applyChangedCompanyTags(SubmitApplyTagValueDTO applyTagValueDTO, LoginUser loginUser) {

    }

    /**
     * 查询可用的标签库
     * @return
     */
    @Override
    public List<CompanyTagsCore> listUseableCompanyTagsCore() {
        return this.list(new LambdaQueryWrapper<CompanyTagsCore>().eq(CompanyTagsCore::getDelFlag,YesNoFlag.NO));
    }

    /**
     * 获取标签可见范围
     * @param tagId
     * @return
     */
    @Override
    public TagVisibleRange getTagVisibleRange(Long tagId) {
        TagVisibleRange tagVisibleRange = new TagVisibleRange();
        if(tagId==0){
            //100
           tagVisibleRange.setR100(new TagVisible(false));
            //101
           List<CompanyCore> companyCores =  companyCoreService.list(new LambdaQueryWrapper<CompanyCore>().select(CompanyCore::getId,CompanyCore::getCompanyName,CompanyCore::getMemberId,CompanyCore::getMemberName)
                    .eq(CompanyCore::getStatus,CompanyStatus.审核通过).eq(CompanyCore::getShowFlag,YesNoFlag.YES).eq(CompanyCore::getDelFlag,DeleteFlag.NO));
           tagVisibleRange.setR101(new CompanyTagVisible(new ArrayList<>(),companyCores));
            //102
            //获取所有的职能部门
            SysDept sysDept = new SysDept();
            sysDept.setParentId(101L);
            List<SysDept> deptList =  sysDeptService.toBizDeptList(sysDeptService.selectDeptList(sysDept));
            List<BranchMember> branchMembers = branchMemberService.list(new LambdaQueryWrapper<BranchMember>().select(BranchMember::getBranchId,BranchMember::getMemberId,BranchMember::getMemberName)
                    .eq(BranchMember::getDelFlag, YesNoFlag.NO));
            tagVisibleRange.setR102(new BranchTagVisible(null,deptList,null,branchMembers));
            return tagVisibleRange;
        }
        else {
            //查询已有标签的
            CompanyTagsCore companyTagCore = companyTagsCoreService.getById(tagId);
            TagVisibleRange visible = companyTagCore.getVisible();
            //101
            List<CompanyCore> companyCores =  companyCoreService.list(new LambdaQueryWrapper<CompanyCore>().select(CompanyCore::getId,CompanyCore::getCompanyName,CompanyCore::getMemberId,CompanyCore::getMemberName)
                    .eq(CompanyCore::getStatus,CompanyStatus.审核通过).eq(CompanyCore::getShowFlag,YesNoFlag.YES).eq(CompanyCore::getDelFlag,DeleteFlag.NO));
            tagVisibleRange.setR101(new CompanyTagVisible(visible.getR101().getCompanyMemberIds(), companyCores));
            //102
            SysDept sysDept = new SysDept();
            sysDept.setParentId(101L);
            List<SysDept> deptList =  sysDeptService.toBizDeptList(sysDeptService.selectDeptList(sysDept));
            List<BranchMember> branchMembers = branchMemberService.list(new LambdaQueryWrapper<BranchMember>().select(BranchMember::getBranchId,BranchMember::getMemberId,BranchMember::getMemberName)
                    .eq(BranchMember::getDelFlag, YesNoFlag.NO));
           /* List<Long> branchIds = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());
            List<Long> branchMemberIds = branchMembers.stream().map(BranchMember::getMemberId).collect(Collectors.toList());*/
            tagVisibleRange.setR102(new BranchTagVisible(visible.getR102().getBranchIds(), deptList,visible.getR102().getBranchMemberIds(), branchMembers));
            return tagVisibleRange;
        }
    }

    /**
     * 保存小程序选择的标签
     * @param companyTagUpdateDTO
     * @param loginUser
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCompanyTags(CompanyTagUpdateDTO companyTagUpdateDTO, LoginUser loginUser) {
        Long companyId = companyTagUpdateDTO.getCompanyId();
        CompanyCore companyCore = new CompanyCore();  //目标企业
        if(ObjUtil.isNull(companyId)){
            if(loginUser.getMember()!=null && MemberRoleConstant.企业用户.equals(loginUser.getMember().getRoleId())){
                companyCore = companyCore.selectOne(new LambdaQueryWrapper<CompanyCore>().eq(CompanyCore::getMemberId,loginUser.getMember().getId()));
            }
        }
        else{
            companyCore = companyCore.selectById(companyTagUpdateDTO.getCompanyId());
        }
        CompanyTagsCore companyTagCore = this.getById(companyTagUpdateDTO.getTagId());
        if(ObjUtil.isNull(companyTagCore)){
            throw new ServiceException("找不到对应的标签");
        }
        if(companyTagCore.getTagType()==TagType.数字){
           boolean result = NumberUtil.isNumber(companyTagUpdateDTO.getTagValue());
           if(!result){
               throw new ServiceException("填写的值必须为数字");
           }
        }
        else if(companyTagCore.getTagType()==TagType.选择||companyTagCore.getTagType()==TagType.是否显示){
            List<String> options = Arrays.asList(companyTagCore.getTagOptions().split(","));
            if(!options.contains(companyTagUpdateDTO.getTagValue())){
                throw new ServiceException("选择的标签值不正确");
            }
        }
        //判断当前企业是否有此标签
        CompanyTags companyTags = companyTagsService.getCompanyTagsByCompanyAndTagId(companyCore.getId(), companyTagUpdateDTO.getTagId());
        if(ObjUtil.isNull(companyTags)){
            companyTags = new CompanyTags();
            companyTags.setCompanyId(companyId);
            companyTags.setTagId(companyTagCore.getId());
            companyTags.setTagName(companyTagCore.getTagName());
            companyTags.setVisible(companyTagCore.getVisible());
            companyTags.setTagType(companyTagCore.getTagType());
            companyTags.setTagUnit(companyTagCore.getTagUnit());
            companyTags.setIsApply(companyTagCore.getIsApply());
            companyTags.setDelFlag(YesNoFlag.NO);
            companyTags.setCreateBy(loginUser.getUsername());
            companyTags.setCreateTime(new Date());
        }
        if(ObjUtil.isNotNull(companyTags)){
            if(companyTagCore.getIsApply()==YesNoFlag.YES && loginUser.getMember()!=null && MemberRoleConstant.企业用户.equals(loginUser.getMember().getRoleId())){
                companyTags.setApplyStatus(YesNoFlag.NO);
                companyTags.setTagValueNew(companyTagUpdateDTO.getTagValue());
            }
            else{
                companyTags.setApplyStatus(YesNoFlag.YES);
                companyTags.setTagValue(companyTagUpdateDTO.getTagValue());
            }
            companyTags.setUpdateBy(loginUser.getUsername());
            companyTags.setUpdateTime(new Date());
        }
        companyTagsService.saveOrUpdate(companyTags);
    }


}
